<template>
  <base-breadcrumb class="app-container">
    <div class="container">
      <a-spin
        :spinning="progressing"
        :tip="progressingTips || '处理中...'"
      >
        <a-card>
          <title-name title="项目业态信息" />
          <a-row>
            <a-form-model
              ref="ruleForm"
              :model="form"
              :rules="rules"
            >
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="项目业态"
                  prop="formatName"
                  :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                  :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                >
                  <BaseInput
                    v-model="form.formatName"
                    :disabled="type == 'view'"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="状态"
                  :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                  :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                  prop="enabledStatus"
                >
                  <a-select
                    v-model="form.enabledStatus"
                    :get-popup-container="getPopupContainer"
                    style="width: 100%"
                    :disabled="type == 'view'"
                  >
                    <a-select-option :value="1">
                      可用
                    </a-select-option>
                    <a-select-option :value="0">
                      不可用
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-form-model>
          </a-row>
          <div>
            <title-name title="标准WBS模板" />
            <div class="button-bar">
              <a-button
                type="primary"
                :disabled="type == 'view' || confirmLoadings || !selectedData"
                @click="addSameNode"
              >
                新增同级节点
              </a-button>
              <a-button
                type="primary"
                :disabled="type == 'view' || confirmLoadings || !selectedData || selectedData.nodeLevel === 3"
                @click="addNextNode"
              >
                新增下级节点
              </a-button>
              <a-button
                type="primary"
                @click="handleExportMarketingList"
              >
                导出
              </a-button>
              <a-button
                v-if="type !== 'view'"
                v-btnPermission="'pm_007_ref_04'"
                @click="refreshIndex"
              >
                刷新WBS模板序号
              </a-button>
              <a-button
                type="default"
                :disabled="
                  type == 'view' ||
                    confirmLoadings ||
                    !selectedData ||
                    selectedData.nodeOrder == '0' ||
                    selectedData.nodeOrder == '2'
                "
                @click="action('moveUp')"
              >
                上移
              </a-button>
              <a-button
                type="default"
                :disabled="
                  type == 'view' ||
                    confirmLoadings ||
                    !selectedData ||
                    selectedData.nodeOrder == '1' ||
                    selectedData.nodeOrder == '2'
                "
                @click="action('moveDown')"
              >
                下移
              </a-button>
              <a-button
                type="default"
                :disabled="type == 'view' || confirmLoadings || !selectedData || selectedData.nodeLevel == '1'"
                @click="action('outdent')"
              >
                升级
              </a-button>
              <a-button
                type="default"
                :disabled="
                  type == 'view' ||
                    confirmLoadings ||
                    !selectedData ||
                    selectedData.nodeLevel == '3' ||
                    selectedData.nodeOrder === '2' ||
                    selectedData.nodeOrder === '0'
                "
                @click="action('indent')"
              >
                降级
              </a-button>
              <a-button
                type="default"
                :disabled="
                  type == 'view' ||
                    confirmLoadings ||
                    !selectedData ||
                    (selectedData.nodeOrder === '2' && selectedData.nodeLevel === 1)
                "
                @click="action('del')"
              >
                删除节点
              </a-button>
              <a-button
                type="primary"
                @click="showDrawer()"
              >
                查看甘特图
              </a-button>
              <a-button
                type="primary"
                :disabled="loading"
                @click="$refs.bigDataTable.setAllTreeExpansion()"
              >
                展开全部
              </a-button>
              <a-button
                type="primary"
                :disabled="loading"
                @click="$refs.bigDataTable.clearTreeExpand()"
              >
                收起全部
              </a-button>
            </div>
          </div>
          <div class="gantt-layout">
            <div class="pub-table-select-count">
              <a-icon
                type="info-circle"
                theme="twoTone"
              />
              <span style="margin-right: 12px">
                项目业态：<span class="totalNum">{{ total.formatName }} </span> | 节点共 ：<span
                  class="totalNum"
                >{{ total.nodeTotal }} 项
                </span>
                | 一级节点共<span class="totalNum">{{ total.firstNodeNum }} 项 </span> | 二级节点共<span
                  class="totalNum"
                >{{ total.secondNodeNum }} 项
                </span>
                | 三级节点共<span class="totalNum">{{ total.thirdNodeNum }} 项 </span> | 周期天数<span
                  class="totalNum"
                >{{ total.cycleDays }}
                </span>
              </span>
            </div>


            <a-drawer
              ref="ganttDrawer"
              title=""
              placement="right"
              :closable="false"
              :z-index="10"
              :get-container="false"
              :visible="visible"
              :body-style="{ padding: '0' }"
              :wrap-style="{ position: 'absolute' }"
              width="70%"
              :after-visible-change="afterVisibleChange"
              @close="onClose"
            >
              <gantt
                ref="ganttCom"
                class="left-container"
                :columns="ganttColumns"
                :plugins="plugins"
                :tasks="tasks"
                :heigh="ganttHeight"
                @task-deleted="deleteTask"
                @task-updated="logTaskUpdate"
                @link-updated="logLinkUpdate"
                @task-addModal="addModal"
                @task-selected="selectTask"
              />
            </a-drawer>
            <umi-table
              ref="bigDataTable"
              show-header-overflow
              show-body-overflow
              :height="500"
              :row-height="50"
              :tree-config="{
                children: 'children',
                expandAll: false,
              }"
              row-key="nodeId"
              row-id="nodeId"
              :use-virtual="true"
              border
              :row-class-name="rowClassNames"
              @row-click="handleClickRow"
            >
              <u-table-column
                v-for="item in columns"
                :key="item.id"
                :prop="item.dataIndex"
                :label="item.title"
                :width="item.width"
                :tree-node="item.dataIndex === 'name'"
                align="center"
              >
                <template v-slot="{ row }">
                  <div
                    v-if="item.scopedSlots"
                    :title="row[item.dataIndex]"
                  >
                    <!--阶段/类别-->
                    <div
                      v-if="item.dataIndex === 'name'"
                      class="table-form-box"
                    >
                      <BaseTextarea
                        v-if="row.nodeLevel != '3' && type == 'edit'"
                        v-model="row.name"
                        placeholder="请输入"
                        :auto-size="{minRows: 2, maxRows: 2}"
                        :show-limit-tip="false"
                        :show-stretch="false"
                        @change="changeName(row)"
                        @blur="blurData"
                      />
                      <span
                        v-else
                        style="display:inline-block;"
                      >{{ row.name }}</span>
                    </div>
                    <!--业务事项-->
                    <div
                      v-if="item.dataIndex === 'businessMatters'"
                      class="table-form-box"
                    >
                      <BaseTextarea
                        v-if="row.nodeLevel == '3' && type == 'edit'"
                        v-model="row.businessMatters"
                        placeholder="请输入"
                        :auto-size="{minRows: 2, maxRows: 2}"
                        :show-limit-tip="false"
                        :show-stretch="false"
                        @blur="changeMatter"
                      />
                      <span v-else>{{ row.businessMatters }}</span>
                    </div>
                    <!-- 管控级别 -->
                    <div
                      v-if="item.dataIndex === 'level'"
                      class="table-form-box"
                    >
                      <a-select
                        v-if="row.nodeLevel == '3' && type == 'edit'"
                        v-model="row.controlLevelId"
                        :get-popup-container="getPopupContainer"
                        :disabled="type == 'view'"
                        placeholder="请选择"
                        style="width: 100px"
                        @change="changeLevel"
                      >
                        <a-select-option
                          v-for="item in nodeList"
                          :key="item.controlLevelId"
                          :value="item.controlLevelId"
                        >
                          {{
                            item.controlLevelName
                          }}
                        </a-select-option>
                      </a-select>
                      <span v-else>{{ row.controlLevelName }}</span>
                    </div>
                    <!-- 周期 -->
                    <div
                      v-if="item.dataIndex === 'duration'"
                      class="table-form-box"
                    >
                      <BaseInputNumber
                        v-if="row.nodeLevel == '3' && type == 'edit'"
                        v-model="row.duration"
                        placeholder="请输入"
                        :min="0"
                        :max="2000"
                        style="width: 100px"
                        :disabled="confirmLoadings"
                        @blur="editduration"
                      />
                      <span v-else>{{ row.duration }}</span>
                    </div>
                    <!-- 标准开始时间 -->
                    <div
                      v-if="item.dataIndex === 'startDate'"
                      class="table-form-box"
                    >
                      <BaseInputNumber
                        v-if="row.nodeLevel == '3' && type == 'edit'"
                        v-model="row.startDate"
                        placeholder="请输入"
                        :min="0"
                        :max="2000"
                        style="width: 100px"
                        :disabled="confirmLoadings"
                        @blur="editstartDate"
                      />
                      <span v-else>{{ row.startDate }}</span>
                    </div>
                    <!-- 时间标准 -->
                    <div v-if="item.dataIndex === 'dateStandard'">
                      <div class="table-form-box">
                        <a-select
                          v-if="row.nodeLevel == '3' && type == 'edit'"
                          v-model="row.dateStandard"
                          :get-popup-container="getPopupContainer"
                          placeholder="请选择"
                          style="width: 100px"
                          :disabled="confirmLoadings"
                          @change="changedateStandard"
                        >
                          <a-select-option :value="1">
                            开工日前
                          </a-select-option>
                          <a-select-option :value="0">
                            开工日后
                          </a-select-option>
                        </a-select>
                        <span v-else>{{ row.dateStandardName }}</span>
                      </div>
                    </div>
                    <!-- 标准完成时间 -->
                    <div v-if="item.dataIndex === 'completeDate'">
                      <div
                        v-if="row.nodeLevel == '3'"
                        class="table-form-box"
                      >
                        <span v-if="row.completeDate < 0">开工日前{{ Math.abs(row.completeDate) }}天</span>
                        <span v-if="row.completeDate > 0">开工日后{{ row.completeDate }}天</span>
                        <span v-if="row.completeDate == 0">开工日</span>
                      </div>
                    </div>
                    <!-- 完成标准 -->
                    <div v-if="item.dataIndex === 'completeStandard'">
                      <div class="table-form-box">
                        <BaseTextarea
                          v-if="row.nodeLevel == '3' && type == 'edit'"
                          v-model="row.completeStandard"
                          placeholder="请输入"
                          :auto-size="{minRows: 2, maxRows: 2}"
                          :show-limit-tip="false"
                          :show-stretch="false"
                          @blur="changecompleteStandard"
                        />
                        <span v-else>{{ row.completeStandard }}</span>
                      </div>
                    </div>

                    <!-- 验证资料 -->
                    <div
                      v-if="item.dataIndex === 'verifyDoc'"
                      class="table-form-box"
                    >
                      <BaseTextarea
                        v-if="row.nodeLevel == '3' && type == 'edit'"
                        v-model="row.verifyDoc"
                        placeholder="请输入"
                        :auto-size="{minRows: 2, maxRows: 2}"
                        :show-limit-tip="false"
                        :show-stretch="false"
                        @blur="changeverifyDoc"
                      />
                      <span v-else>{{ row.verifyDoc }}</span>
                    </div>
                    <!-- 第一责任人 -->
                    <div
                      v-if="item.dataIndex === 'firstResponsible'"
                      class="table-form-box"
                    >
                      <span v-if="row.firstResponsible"><ellipsis
                        :length="18"
                        tooltip
                      >{{ row.firstResponsible }}</ellipsis></span>
                      <a
                        v-if="type != 'view' && row.nodeLevel == '3' && row.firstResponsible"
                        @click="handleBind(row)"
                      >(重新选择)</a>
                      <a
                        v-if="type != 'view' && row.nodeLevel == '3' && !row.firstResponsible"
                        @click="handleBind(row)"
                      >选择第一责任人</a>
                    </div>
                  </div>
                  <span
                    v-else
                    :title="row[item.dataIndex]"
                  >
                    {{ row[item.dataIndex] }}
                  </span>
                </template>
              </u-table-column>
            </umi-table>
          </div>
        </a-card>
      </a-spin>
    </div>

    <modal
      :id="currentId"
      :visible="bindOrgVisible"
      :org-query="orgQuery"
      :screening="screening"
      @handleCancelFirstRes="handleCancelFirstRes"
      @handleOk="handleOk"
    />
    <div class="page-btn-right-top">
      <a-button
        :disabled="type == 'view'"
        :loading="loading"
        type="primary"
        @click="submit"
      >
        提交
      </a-button>
      <a-button
        type="primary"
        style="margin: 0 12px"
        @click="cancel"
      >
        关闭
      </a-button>
    </div>
  </base-breadcrumb>
</template>
<script>
import { gantt } from 'dhtmlx-gantt'
import {
  getWbsTemplate,
  addSameNode,
  addNextNode,
  editNode,
  deleteNode,
  editTemplateNode,
  getNodeControl,
  editWbsTemplateList,
  refreshTemplateList,
  getWbsTemplateExport
} from '@/api/template'
import Gantt from '../gantt/gantt'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
import * as moment from 'moment'
import modal from '@/components/SelectJobs' // 第一责任人
import { UTable, UTableColumn } from 'umy-ui'
import Ellipsis from '../../../components/Ellipsis/Ellipsis'

const columns = [
  {
    title: '编号',
    width: 60,
    dataIndex: 'index',
  },
  {
    title: '阶段/类别',
    align: 'left',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' },
    width: 370,
  },
  {
    title: '业务事项',
    align: 'center',
    dataIndex: 'businessMatters',
    width: 300,
    scopedSlots: { customRender: 'businessMatters' },
  },
  {
    title: '管控级别',
    dataIndex: 'level',
    align: 'center',
    scopedSlots: { customRender: 'level' },
    width: 120,
  },
  {
    title: '周期',
    dataIndex: 'duration',
    align: 'center',
    width: 120,
    scopedSlots: { customRender: 'duration' },
  },
  {
    title: '时间标准',
    dataIndex: 'dateStandard',
    align: 'center',
    scopedSlots: { customRender: 'dateStandard' },
    width: 120,
  },
  {
    title: '标准开始时间',
    dataIndex: 'startDate',
    align: 'center',
    scopedSlots: { customRender: 'startDate' },
    width: 120,
  },
  {
    title: '标准完成时间',
    dataIndex: 'completeDate',
    align: 'center',
    scopedSlots: { customRender: 'completeDate' },
    width: 120,
  },
  {
    title: '完成标准',
    dataIndex: 'completeStandard',
    align: 'center',
    scopedSlots: { customRender: 'completeStandard' },
    width: 420,
    ellipsis: true,
  },
  {
    title: '验证资料',
    dataIndex: 'verifyDoc',
    align: 'center',
    width: 300,
    scopedSlots: { customRender: 'verifyDoc' },
    ellipsis: true,
  },
  {
    title: '第一责任人',
    width: 300,
    dataIndex: 'firstResponsible',
    align: 'center',
    scopedSlots: { customRender: 'firstResponsible' },
    ellipsis: true,
  },
]

export default {
  name: 'DhtmlxGantt',
  components: {
    Ellipsis,
    Gantt,
    modal,
    umiTable: UTable,
    UTableColumn,
  },
  data() {
    return {
      today: '2020-11-23',
      ganttHeight: 661,

      // 选择第一责任人
      progressing: false,
      progressingTips: '处理中...',
      levelOption: '',
      disabled: false,
      currentId: '',
      tableData: [],
      startDates: '',
      type: '',
      locale,
      total: {},
      tasks: { data: [], links: [] },
      columns,
      templateId: '',
      addLevel: '',
      rowSelection: {},
      selectedRowKeys: [],
      responsList: [],
      resultData: {},
      saveSelectRows: [],
      bindOrgVisible: false,
      ganttColumns: [],
      firstResponsible: [],
      loading: false,
      preTasks: [],
      selectLevel: '',
      taskType: 'task',
      modalTitle: '新增节点',
      confirmLoadings: false,
      nodeList: '',
      addVisible: false,
      visible: false,
      selectId: '',
      selectedData: null,
      taskTemplateVisible: false,
      plugins: {
        undo: true,
        drag_timeline: true,
      },
      messages: [],
      selectedTask: null,
      form: {
        enabledStatus: '',
        formatName: '',
      },
      rules: {
        formatName: [{ required: true, message: '请填写项目业态名称', trigger: 'blur' }],
        enabledStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
      },
      orgQuery: { common: true },
      // 第一责任人用基础组织架构(false)
      screening: false,
      cash:[],
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, {})
  },
  watch: {
    tableData(list) {
      if(this.$refs.bigDataTable) {
        // 获取之前展开数据
        const expandRecords = this.$refs.bigDataTable.getTreeExpandRecords()
        // 获取之前滚动高度(表格实例上的scrollTop属性，在滚动到底部时会小于真实的scrollTop值，因此直接从dom获取真实滚动高度)
        const scrollTop = this.$refs.bigDataTable.tableExample().bodyWrapper.scrollTop
        // 加载数据
        this.$refs.bigDataTable.reloadData(list).then(() => {
          // 数据加载完成出现之后，打开之前的展开行
          expandRecords.forEach(row => {
            this.$refs.bigDataTable.setTreeExpansion(row, true)
          })
          // 还原之前滚动高度
          this.$refs.bigDataTable.pagingScrollTopLeft(scrollTop)
        })
      }
    },
  },
  created() {
    this.today = moment().format('yyyy-MM-DD')

    this.currentId = JSON.parse(sessionStorage.getItem('ycloud-user_info')).id
    this.templateId = this.$route.query.wbsTemplateId
    this.type = this.$route.query.type
    this.getWbsTemplateList(true)

    this.getNodeControl()
    localStorage.removeItem('task')
    localStorage.removeItem('link')
    this.rowSelection = this.getRowSelection()
    this.tasks.data = []
    this.tasks.links = []
    this.ganttColumns = [
      {
        name: 'sortNum',
        label: '编号',
        align: 'center',
        resize: true,
        tree: false,
        width: 40,
        template: function (obj) {
          return obj.$index + 1
        },
      },
      {
        name: 'name',
        label: '阶段/类别',
        align: 'left',
        resize: true,
        tree: false,
        width: 140,
        template: function (obj) {
          return obj.text
        },
      },
    ]

    gantt.config.date_format = '%Y-%m-%d'
    const cfg = gantt.config
    const strToDate = gantt.date.str_to_date(cfg.date_format, cfg.server_utc)
    gantt.templates.parse_date = function (date) {
      return strToDate(date)
    }
  },
  methods: {

    // 导出复杂表头
    handleExportMarketingList() {
      getWbsTemplateExport({templateId:this.templateId}).then(res=>{
        if(res.code == 200 || res.data.code == 200){
          this.cash = res.data

          require.ensure([], () => {
            const {export_json_to_excel_1} = require('@/components/exportExcel/Export2Excel2');
            //multiHeader数组里面添加的是一级表头的名称，要按顺序添加每个表头的的名称，如果遇到横向合并单元格的地方，合并了多少个单元格，就要留几个空字符串占位
            // const multiHeader = [['标准Wbs','','','','','','','','','','','',]];

            const multiHeader =
              [['序号','阶段','类别','管控级别','业务事项','周期',
                '时间标准','标准开始时间','标准结束时间','完成标准','上传验证资料','完成责任人'
              ]];


            //filterVal数组里面放的是表头title对应的字段名称
            const filterVal = [
              'sortNum',"stage","category","controlLevel", "businessMatters","duration",
              "dateStandard","standardStartTime", "standardEndTime","completeStandard","verifyDoc","firstResponsible",
            ];


            // this.cash是后端返回来的数组，用map方法遍历，这里你可以改你想要的数据，最后用return将每个字段一次返回就好啦
            const list = this.cash.map((item, key) => {

              return {
                sortNum: item.sortNum || null,
                stage: item.stage || null,
                category: item.category || null,
                controlLevel: item.controlLevel || null,
                businessMatters: item.businessMatters || null,
                duration: item.duration || null,

                dateStandard: item.dateStandard || null,
                standardStartTime: item.standardStartTime || null,
                standardEndTime: item.standardEndTime || null,
                completeStandard: item.completeStandard || null,
                verifyDoc: item.verifyDoc || null,
                firstResponsible: item.firstResponsible || null,
              }
            });
            // merges是进行所有表头的单元格合并，数组里面的每个元素的填写规则是：按从左往右的顺序依次填写，
            // 字母是指excel里面的第几列，数字表示第几行，如果是上下的单元格合并，就是按从上往下填写，比
            // 如'A1:A2'代表的是A列的第一个单元格和A列的第二个单元格合并，如果是左右的单元格合并，也是从左往右填写，同理，
            const merges =
              ['A1:A1', 'B1:B1', 'C1:C1','D1:D1','E1:E1','F1:F1','G1:G1','H1:H1','I1:I1','J1:J1','K1:K1','L1:L1'];

            // const merges =
            //   ['A1:L1', 'B2:B2', 'C2:C2','D2:D2','E2:E2','F2:F2','G2:G2','H2:H2','I2:I2','J2:J2','K2:K2','L2:L2'];
            if(list) {
              const data = this.formatJson(filterVal, list); // 生成json数据
              export_json_to_excel_1({
                multiHeader, // 这里是第一行的表头
                data,
                filename: '标准Wbs',  //这里填的是导出excel的名称
                merges,
              });
            } else {
              alert("暂无无数据");
            }
          });

        }
      })

    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },

    // 查看甘特图
    showDrawer() {
      this.visible = !this.visible

      // 重新加载甘特图计划时间段数据



      // this.$refs.bigDataTable.reloadData
    },
    selectTask: function (task) {
      console.log('当前选中行数据:', task)
      this.selectedTask = task
      // gantt.selectTask(task.id);
    },
    deleteTask: function (taskId) {
      this.selectedTask = task
      gantt.deleteTask(task.id)
    },
    logTaskUpdate(id, mode, task) {
      const text = task && task.text ? ` (${task.text})` : ''
      const message = `Task ${mode}: ${id} ${text}`
      this.addMessage(message)
    },
    logLinkUpdate(id, mode, link) {
      let message = `Link ${mode}: ${id}`
      if (link) {
        message += ` ( source: ${link.source}, target: ${link.target} )`
      }
      this.addMessage(message)
    },

    addModal(task) {

      this.confirmLoading = false
      const tasks = gantt.getTaskByTime()
      let parent = gantt.getSelectedId()

      this.addVisible = true

    },
    refreshIndex(){
      refreshTemplateList({templateId:this.templateId}).then(res=>{
        if(res.data.code == 200 || res.code== 200){
           this.getWbsTemplateList(true)
        }
      })
    },
    // 第一责任人
    handleCancelBindOrg(val) {
      // this.bindOrgVisible=val
    },
    handleCancelFirstRes() {
      this.bindOrgVisible = false
    },
    handleBind(data) {
      this.bindOrgVisible = true
    },
    handleOk(value) {
      this.confirmLoadings = true
      this.bindOrgVisible = false
      let firstRes = {
        label: value.jobsSelectedName,
        key: value.jobsSelectedId,
      }
      let data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        firstRes: firstRes,
      }
      editTemplateNode(data).then((res) => {
        if (res) {
          this.getWbsTemplate()
        }
        if ((res.code = 200)) {
          this.confirmLoadings = false
          this.$message.success('修改成功')
        }
      })
    },
    // handleOk(){
    //   this.confirmLoadings=true
    //   this.bindOrgVisible = false
    //   const form = this.$refs.createForm.form
    //   form.validateFields((errors, value) => {
    //     if (errors) {
    //       let firstRes={
    //         label:value.jobsSelectedName[0],
    //         key:value.jobsSelectedId
    //       }
    //       let data={
    //         templateId:this.templateId,
    //         nodeId:this.selectedData.nodeId,
    //         firstRes:firstRes
    //       }
    //       editTemplateNode(data).then((res)=>{
    //         if(res){
    //           this.getWbsTemplate()
    //         }
    //         if(res.code=200){
    //           this.confirmLoadings=false
    //           this.$message.success("修改成功")
    //         }
    //       })
    //
    //     }})
    //
    // },
    // 验证表格内的填写数据项
    handleValidateTables() {
      let flag = true
      const validateEmpty = (val) => {
        if (val === '' || val === undefined || val === null) {
          return false
        }
        return true
      }
      const validateTableData = (list) => {
        for (let i = 0; i < list.length; i++) {
          const record = list[i]
          if (record.nodeLevel != '3' && !validateEmpty(record.name)) {
            this.$message.error('请完善阶段/类别')
            flag = false
            return
          }
          if (record.nodeLevel == '3' && !validateEmpty(record.businessMatters)) {
            this.$message.error('请完善业务事项')
            flag = false
            return
          }
          if (record.nodeLevel == '3' && !validateEmpty(record.controlLevelName)) {
            this.$message.error('请完善管控级别')
            flag = false
            return
          }
          if (record.nodeLevel == '3' && !validateEmpty(record.duration)) {
            this.$message.error('请完善周期')
            flag = false
            return
          }
          if (record.nodeLevel == '3' && !validateEmpty(record.dateStandardName)) {
            this.$message.error('请完善时间标准')
            flag = false
            return
          }
          if (record.nodeLevel == '3' && !validateEmpty(record.startDate)) {
            this.$message.error('请完善标准开始时间')
            flag = false
            return
          }
          if (record.nodeLevel == '3' && !validateEmpty(record.completeStandard)) {
            this.$message.error('请完善完成标准')
            flag = false
            return
          }
          if (record.nodeLevel == '3' && !validateEmpty(record.verifyDoc)) {
            this.$message.error('请完善验证资料')
            flag = false
            return
          }
          if (record.nodeLevel == '3' && !validateEmpty(record.firstResponsible)) {
            this.$message.error('请选择第一责任人')
            flag = false
          }
          record.children && validateTableData(record.children)
        }
      }
      validateTableData(this.tableData)
      return flag
    },
    // 提交
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // if(!this.handleValidateTable()) return
          this.confirmLoadings = true
          const arrList = {
            formatId: this.templateId,
            formatName: this.form.formatName,
            enabledStatus: this.form.enabledStatus,
          }
          editWbsTemplateList(arrList)
            .then((res) => {
              this.confirmLoadings = false
              if ((res.code = 200)) {
                this.$message.success('提交成功')
                this.$multiTab.close(this.$route.fullpath)
              }
            })
            .catch(() => {
              this.confirmLoadings = false
            })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    // 关闭
    cancel() {
      this.$multiTab.close(this.$route.fullpath)
    },
    getNodeControl() {
      getNodeControl({queryDefault: true}).then((res) => {
        this.nodeList = res.data
      })
    },
    changeName(value) {},
    // 标准开始时间
    editstartDate(e) {
      this.confirmLoadings = true
      this.saveSelectRows.startDate = e.target.value
      let startDate = this.saveSelectRows.startDate
      if (!startDate) {
        startDate = 0
      }
      let data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        startDate: startDate,
      }
      editTemplateNode(data)
        .then((res) => {
          if (res) {
            this.getWbsTemplate()
          }
          if (res.code == '200') {
            this.$message.success('修改成功')
            this.confirmLoadings = false
          }
        })
        .catch(() => (this.confirmLoadings = false))
    },
    // 周期
    editduration(e) {
      this.confirmLoadings = true
      this.saveSelectRows.duration = e.target.value
      let duration = this.saveSelectRows.duration
      if (!duration) {
        duration = 0
      }
      let data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        duration: duration,
      }
      editTemplateNode(data)
        .then((res) => {
          if (res) {
            this.getWbsTemplate()
          }
          if (res.code == '200') {
            this.$message.success('修改成功')
            this.confirmLoadings = false
          }
        })
        .catch(() => {
          this.confirmLoadings = false
        })
    },
    // 验证资料
    changeverifyDoc(e) {
      this.saveSelectRows.verifyDoc = e.target.value
      let data = {}
      data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        verifyDoc: this.saveSelectRows.verifyDoc,
      }
      this.confirmLoadings = true
      editTemplateNode(data)
        .then((res) => {
          this.confirmLoadings = false
        })
        .catch(() => {
          this.confirmLoadings = false
        })
    },
    // 完成标准
    changecompleteStandard(e) {
      this.confirmLoadings = true
      this.saveSelectRows.completeStandard = e.target.value
      let data = {}
      data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        completeStandard: this.saveSelectRows.completeStandard,
      }
      editTemplateNode(data)
        .then((res) => {
          this.confirmLoadings = false
        })
        .catch(() => {
          this.confirmLoadings = false
        })
    },
    // 管控节点
    changeLevel(value) {
      this.confirmLoadings = true
      let data = {}
      data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        controlLevelId: value,
      }
      editTemplateNode(data)
        .then((res) => {
          this.confirmLoadings = false
        })
        .catch(() => {
          this.confirmLoadings = false
        })
    },
    // 时间标准
    changedateStandard(value) {
      this.confirmLoadings = true
      let data = {}
      data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        dateStandard: value,
      }
      editTemplateNode(data)
        .then((res) => {
          if (res) {
            this.getWbsTemplate()
          }
          if (res.code == '200') {
            this.$message.success('修改成功')
            this.confirmLoadings = false
          }
        })
        .catch(() => {
          this.confirmLoadings = false
        })
    },

    // 获取模板
    getWbsTemplateList(showLoading) {
      let that = this;
      if (showLoading) {
        that.progressing = true
        that.progressingTips = '加载中...'
      }
      getWbsTemplate(that.templateId)
        .then((res) => {
          that.form = res.data
          that.tableData = []
          that.tableData =  res.data.wbsNodeList
          console.log(res.data.wbsNodeList)
          console.log('data')

          that.tableData.forEach((item1) => {
            if (item1.children) {
              item1.children.forEach((item2) => {
                if (item2.children) {
                  item2.children.forEach((item3) => {
                    if(item3.controlLevelId == null){
                      item3.controlLevelId = undefined
                    }
                    if(item3.dateStandard == null){
                      item3.dateStandard = undefined
                    }
                    if (item3.children) {
                      item3.children.forEach((item4) => {
                        if(item4.controlLevelId == null){
                          item4.controlLevelId = undefined
                        }
                        if(item4.dateStandard == null){
                          item4.dateStandard = undefined
                        }

                        const area = {
                          label: item4.directResPerName,
                          key: item4.directResPerId,
                        }
                        item4.directResPer = area
                      })

                    }
                  })
                }
              })
            }
          })

          that.total = res.data
          that.selectId = that.tableData[0].nodeId
          that.selectedData = that.tableData[0]


          that.renderGantt(that.tableData, true)

          that.progressing = false
          that.progressingTips = '加载中...'

        })

        .catch(() => {
          that.progressing = false
          that.progressingTips = ''
          that.confirmLoadings = false
        })
    },

    initData(orgList) { // 第一种
      if (orgList.length) {
        for (var i = 0; i < orgList.length; i++) {
          if (this.orgIdList.length) {
            for (let j = 0; j < this.orgIdList.length; j++) {
              const orgid = this.orgIdList[j];
              if (orgList[i].controlLevelId == null) {
                orgList[i].controlLevelId = undefined
              }
            }
          }
          if (orgList[i].children.length) { // 如果有 children 则继续递归遍历
            this.initData(orgList[i].children);
          }
        }
      }
      return orgList
    },

    renderGantt(treeData, open) {
      gantt.clearAll()
      const ganttData = {
        data: [],
      }
      const readTreeData = (children, parent) => {
        children.forEach((c) => {
          const data = { ...c, id: c.nodeId, type: c.children ? 'project' : '', parent, open }
          ganttData.data.push(this.valuesToTask(data))
          if (c.children && c.children.length > 0) {
            readTreeData(c.children, c.nodeId, open)
          }
        })
      }
      readTreeData(treeData, null, open)
      gantt.parse(ganttData)
    },
    valuesToTask(values) {
      const _this = this
      return {
        id: values.id || values.nodeId,
        parent: values.parent,
        text: values.name || values.businessMatters,
        name: values.name,
        businessMatters: values.businessMatters,
        start_date: values.start_date || values.startTime || _this.today,
        startDate: values.startDate || values.startTime || _this.today,
        end_date: values.end_date || values.endTime || _this.today,
        endDate: values.endDate || values.endTime || _this.today,
        duration: values.duration,
        parentId: values.workPackId,
        type: values.type,
        preTask: values.preTask,
        matters: values.businessMatters,
        controlLevelName: values.controlLevelName,
        level: values.level,
        responsible: values.responsible,
        firstResponsible: values.firstResponsible,
        nodeLevel: values.nodeLevel,
        nodeId: values.nodeId,
        workPackId: values.workPackId,
        open: values.open,
      }
    },

    getWbsTemplate() {
      this.confirmLoadings = true
      getWbsTemplate(this.templateId)
        .then((res) => {
          this.tableData = []
          this.tableData = res.data.wbsNodeList
          this.total = res.data
          this.confirmLoadings = false
        })
        .catch(() => {
          this.confirmLoadings = false
        })
    },
    // 保存阶段名称
    blurData(e) {
      this.confirmLoadings = true
      this.saveSelectRows.name = e.target.value
      let data = {}
      if (this.selectedData.nodeLevel == 1 || this.selectedData.nodeLevel == 2) {
        data = {
          templateId: this.templateId,
          nodeId: this.selectedData.nodeId,
          parentId: this.selectedData.workPackId,
          workPackName: this.saveSelectRows.name,
        }
      } else {
        data = {
          templateId: this.templateId,
          nodeId: this.selectedData.nodeId,
          name: this.saveSelectRows.name,
        }
      }
      editTemplateNode(data)
        .then((res) => {
          this.confirmLoadings = false
        })
        .catch(() => {
          this.confirmLoadings = false
        })
    },
    changeMatter(e, record) {
      this.confirmLoadings = true
      this.saveSelectRows.businessMatters = e.target.value
      let data = {}
      data = {
        templateId: this.templateId,
        nodeId: this.selectedData.nodeId,
        name: this.saveSelectRows.businessMatters,
      }
      editTemplateNode(data)
        .then((res) => {
          this.confirmLoadings = false
        })
        .catch(() => {
          this.confirmLoadings = false
        })
    },
    handleChange(e) {
      const value = e.target.value
      this.value = value
    },
    // 点击行
    clickRow(record, index) {
      const _this = this
      return {
        on: {
          click: () => {
            _this.selectId = record.nodeId
            _this.selectedData = record
            _this.rowClassNames(record)
          },
        },
      }
    },
    /**
     * 控制umi-table的点击
     */
    handleClickRow(record) {
      this.selectId = record.nodeId
      this.selectedData = record
      this.rowClassNames(record)
    },
    afterVisibleChange(visible) {
      if (visible) {
        gantt.refreshData()
      }
    },
    onClose() {
      this.visible = false
    },

    getChildrenSize(p) {
      let size = 0
      const getChildSize = (p) => {
        if (p.type === 'task') {
          return
        }
        p.children.forEach((c) => {
          if (c.type === 'task') {
            size++
          }
          getChildSize(c)
        })
      }
      getChildSize(p)
      return size
    },
    rowExpand(expanded, task) {
      if (expanded) {
        gantt.open(task.id)
      } else {
        gantt.close(task.id)
      }
    },
    getRowSelection() {
      const _this = this
      return {
        columnWidth: 40,
        type: 'radio',
        hideDefaultSelections: true,
        selectedRowKeys: _this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          _this.selectedData = selectedRows[0]
          _this.selectedRowKeys = selectedRowKeys
        },
        onSelect: (record, selected, selectedRows) => {
          _this.selectedData = record
          _this.selectLevel = record.levelType
        },
        onSelectAll: (selected, selectedRows, changeRows) => {
          _this.selectedData = selectedRows[0]
        },
      }
    },
    // 新增同级节点
    addSameNode() {
      if (!this.selectedData) {
        this.$message.error('请选择节点')
        return false
      } else {
        let _this = this
        this.$confirm({
          okText: '确定',
          cancelText: '取消',
          title: '确定新增同级节点?',
          onOk() {
            _this.confirmLoadings = true
            //如果选择的是一级节点
            if (_this.selectedData.nodeLevel == '1' || _this.selectedData.nodeLevel == '2') {
              addSameNode({ templateId: _this.templateId, parentId: _this.selectedData.nodeId })
                .then((res) => {
                  if (res.code == '200') {
                    _this.confirmLoadings = false
                    _this.getWbsTemplate()
                    _this.$message.success('新增节点成功')
                    _this.resultData = res.data
                  }
                })
                .catch(() => {
                  _this.confirmLoadings = false
                })
            } else {
              addSameNode({
                parentId: _this.selectedData.workPackId,
                templateId: _this.templateId,
                id: _this.selectedData.nodeId,
              })
                .then((res) => {
                  if (res.code == '200') {
                    _this.getWbsTemplate()
                    _this.confirmLoadings = false
                    _this.$message.success('新增成功')
                  }
                })
                .catch(() => {
                  _this.confirmLoadings = false
                })
            }
          },
          onCancel() {},
          class: 'test',
        })
      }
    },
    getPopupContainer(triggerNode) {
      // return triggerNode.parentNode
      return document.body
    },
    // 新增下级节点
    addNextNode() {
      if (!this.selectedData) {
        this.$message.error('请选择节点')
      } else {
        let _this = this
        this.$confirm({
          okText: '确定',
          cancelText: '取消',
          title: '确定新增下级节点?',
          onOk() {
            let list = {}
            _this.confirmLoadings = true
            if (_this.selectedData.nodeLevel == '1' || _this.selectedData.nodeLevel == '2') {
              addNextNode({ id: _this.selectedData.nodeId, templateId: _this.templateId })
                .then((res) => {
                  if (res.code == '200') {
                    _this.getWbsTemplate()
                    _this.confirmLoadings = false
                    _this.$message.success('新增成功')
                    list = res.data
                  }
                })
                .catch(() => {
                  _this.confirmLoadings = false
                })
            } else {
              _this.$message.error('此节点不可新增下级节点')
            }
          },
          onCancel() {},
          class: 'test',
        })
      }
    },
    action(name) {
      // 升级
      if ('outdent' === name) {
        if (!this.selectedData) {
          this.$message.error('请选择节点')
        } else {
          let data = {}
          if (this.selectedData.nodeLevel == 1 || this.selectedData.nodeLevel == 2) {
            data = {
              templateId: this.templateId,
              positionTypeEnum: 2,
              workPackId: this.selectedData.nodeId,
            }
          } else {
            data = {
              templateId: this.templateId,
              positionTypeEnum: 2,
              workId: this.selectedData.nodeId,
            }
          }
          if (this.selectedData.nodeLevel == '1') {
            this.$message.error('当前节点不可升级')
          } else {
            this.confirmLoadings = true
            editNode(data)
              .then((res) => {
                if ((res.code = '200')) {
                  this.selectedData = null
                  this.getWbsTemplate()
                  this.confirmLoadings = false
                  this.$message.success('节点升级成功')
                }
              })
              .catch(() => {
                this.confirmLoadings = false
              })
          }
        }
      }

      // 降级
      if ('indent' === name) {
        if (!this.selectedData) {
          this.$message.error('请选择节点')
        } else {
          let data = {}
          if (this.selectedData.nodeLevel == 1 || this.selectedData.nodeLevel == 2) {
            data = {
              templateId: this.templateId,
              positionTypeEnum: 3,
              workPackId: this.selectedData.nodeId,
            }
          } else {
            data = {
              templateId: this.templateId,
              positionTypeEnum: 3,
              workId: this.selectedData.nodeId,
            }
          }
          if (this.selectedData.nodeLevel == '3') {
            this.$message.error('当前节点不可降级')
          } else {
            this.confirmLoadings = true
            editNode(data)
              .then((res) => {
                if ((res.code = '200')) {
                  this.selectedData = null
                  this.getWbsTemplate()
                  this.confirmLoadings = false
                  this.$message.success('节点降级成功')
                }
              })
              .catch(() => {
                this.confirmLoadings = false
              })
          }
        }
      }

      // 上移
      if ('moveUp' === name) {
        if (!this.selectedData) {
          this.$message.error('请选择节点')
        } else {
          let data = {}
          if (this.selectedData.nodeLevel == 1 || this.selectedData.nodeLevel == 2) {
            data = {
              templateId: this.templateId,
              positionTypeEnum: 0,
              workPackId: this.selectedData.nodeId,
            }
          } else {
            data = {
              templateId: this.templateId,
              positionTypeEnum: 0,
              workId: this.selectedData.nodeId,
            }
          }
          if (this.selectedData.nodeOrder == '0' || this.selectedData.nodeOrder == '2') {
            this.$message.error('当前节点不可上移')
          } else {
            this.confirmLoadings = true
            editNode(data)
              .then((res) => {
                if (res.code == '200') {
                  this.getWbsTemplate()
                  this.confirmLoadings = false
                  this.$message.success('节点上移成功')
                  this.selectedData = null //res.data
                } else {
                }
              })
              .catch(() => {
                this.confirmLoadings = false
              })
          }
        }
      }

      // 下移
      if ('moveDown' === name) {
        if (!this.selectedData) {
          this.$message.error('请选择节点')
        } else {
          let data = {}
          if (this.selectedData.nodeLevel == 1 || this.selectedData.nodeLevel == 2) {
            data = {
              templateId: this.templateId,
              positionTypeEnum: 1,
              workPackId: this.selectedData.nodeId,
            }
          } else {
            data = {
              templateId: this.templateId,
              positionTypeEnum: 1,
              workId: this.selectedData.nodeId,
            }
          }
          if (this.selectedData.nodeOrder == '1' || this.selectedData.nodeOrder == '2') {
            this.$message.error('当前节点不可下移')
          } else {
            this.confirmLoadings = true
            editNode(data)
              .then((res) => {
                if (res.code == '200') {
                  this.getWbsTemplate()
                  this.confirmLoadings = false
                  this.$message.success('节点下移成功')
                  this.selectedData = null //res.data
                }
              })
              .catch(() => {
                this.confirmLoadings = false
              })
          }
        }
      }

      // 删除节点
      if ('del' === name) {
        let task_id = gantt.getSelectedId()
        if (!this.selectedData) {
          this.$message.warn('请选择节点')
        } else {
          if (
            (this.tableData.length == 1 && !this.tableData[0].children) ||
            (this.tableData.length == 1 && this.selectedData.nodeId == this.tableData[0].nodeId)
          ) {
            this.$message.error('不能删除')
          } else {
            let _this = this
            this.$confirm({
              okText: '删除',
              okType: 'danger',
              cancelText: '取消',
              title: '删除当前选择的节点?',
              onOk() {
                _this.confirmLoadings = true
                let data = {}
                if (_this.selectedData.nodeLevel == 1 || _this.selectedData.nodeLevel == 2) {
                  data = {
                    workPackId: _this.selectedData.nodeId,
                    templateId: _this.templateId,
                  }
                } else {
                  data = {
                    templateId: _this.templateId,
                    parentId: _this.selectedData.workPackId,
                    id: _this.selectedData.nodeId,
                  }
                }
                deleteNode(data)
                  .then((res) => {
                    if ((res.code = '200')) {
                      _this.$message.success('节点删除成功')
                      _this.getWbsTemplate()
                      _this.confirmLoadings = false
                      _this.selectedData = null
                    }
                  })
                  .catch(() => {
                    _this.confirmLoadings = false
                  })
              },
              onCancel() {},
              class: 'test',
            })
          }
        }
      } else {
      }
    },
    rowClassNames(record) {
      if (this.selectId == record.nodeId) {
        return 'clickRowStyle'
      }
    },
  },
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';
@{deep} .plTableBox .el-table td {
  padding: 2px 0;
  border-right: 0;
  height: 40px!important;
}
@{deep} .plTableBox .el-table th{
 padding: 8px 0;
}
.table-form-box {
  @{deep} textarea.ant-input {
    height: 42px !important;
    min-height: 42px !important;
    padding: 1px 10px;
  }
}
</style>

<style scoped>
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
/deep/ .ant-table-body .clickRowStyle {
  background-color: rgb(230, 243, 252);
}
/deep/ .ant-pro-basicLayout-children-content-wrap {
  flex: 1;
}
.gantt-layout {
  position: relative;
}
/deep/ .ant-table-thead th {
  height: 60px;
  line-height: 60px;
  padding: 0;
}
/deep/ .ant-table-placeholder {
  height: 600px;
}
/deep/ .gantt-layout .ant-table-body {
  min-height: 600px;
}
/deep/ .ant-drawer-content-wrapper {
  box-shadow: none !important;
}
/deep/ .ant-table-selection-column {
  width: 40px;
}

.button-bar {
  margin-bottom: 10px;
}

.button-bar > button:not(:first-child) {
  margin-left: 10px;
}
/deep/ .ant-modal-body {
  padding: 0;
}

td {
  display: flex;
}
/* /deep/ .ant-select:not(.ant-pagination-options-size-changer) .ant-select-selection, .ant-input-number{
    height:100% !important;
    width:100px !important
} */
input[type='text'],
input[type='password'],
input[type='number'],
textarea {
  width: 100%;
  height: 28px;
}
.ant-calendar-picker {
  width: 200px;
  height: 28px;
}
.ant-cascader-picker {
  width: 100%;
  height: 28px;
}
form .ant-select,
form .ant-cascader-picker {
  width: 100%;
  height: 28px;
}
.ant-calendar-picker-input.ant-input {
  width: 200px;
  height: 28px;
}
.total div {
  padding: 0 5px;
}
/deep/ .ant-table-tbody > tr > td {
  padding: 5px !important;
}
</style>
